<template>
  <div class="bigbox">
    <div class="topbox">
      <el-form
        :model="form"
        ref="form"
        label-position="left"
        label-width="80px"
        onsubmit="return false"
      >
        <el-row :gutter="20">
          <el-col :span="5">
            <el-form-item label="用电企业">
              <FilterSelect2
                v-model="form.companyId"
                :optionlist="companyList"
                :valuekey="{ name: 'name', value: 'id' }"
                @changeSelect="companyChange"
              ></FilterSelect2>
            </el-form-item>
          </el-col>
          <el-col :span="6" style="margin-top: 4px; display: flex">
            <el-radio-group
              size="small"
              v-model="radio"
              style="margin-right: 20px"
            >
              <el-radio-button label="日" />
              <el-radio-button label="月" />
              <el-radio-button label="年" />
            </el-radio-group>
            <el-date-picker
              style="flex: 1"
              size="small"
              v-model="date"
              :type="
                this.radio == '日'
                  ? 'date'
                  : this.radio == '月'
                  ? 'month'
                  : 'year'
              "
              :format="
                this.radio == '日'
                  ? 'yyyy-MM-dd'
                  : this.radio == '月'
                  ? 'yyyy-MM'
                  : 'yyyy'
              "
              placeholder="选择时间"
            >
            </el-date-picker>
          </el-col>
          <el-col :span="13" style="text-align: right">
            <el-form-item>
              <Twobtn @chaxun="chaxun" @chongzhi="chongzhi"></Twobtn>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="bodybox">
      <div class="bottom">
        <div class="top2">
          <div class="tit2"></div>
          <TopTile
            @command="command"
            @daochu="daochu"
            @shuaxin="shuaxin"
          ></TopTile>
        </div>
        <el-table
          ref="table"
          :size="iissize"
          v-loading="tableLoading"
          border
          height="42vh"
          :header-cell-style="{ 'text-align': 'center', background: '#f5f5f5' }"
          v-bind="$attrs"
          style="width: 100%"
          highlight-current-row
          @current-change="getLineList"
          :data="tableList"
        >
          <template slot="empty">
            <el-empty description="暂无数据"></el-empty>
          </template>
          <el-table-column
            v-for="(item, index) in tableConfig"
            :key="index"
            :prop="item.prop"
            :label="item.label"
            :type="item.type"
            :align="item.align"
            :width="item.width"
            :formatter="item.formatter"
          >
          </el-table-column>
          <template>
            <!-- 插槽 自定义按钮 -->
            <slot></slot>
          </template>
        </el-table>
        <!-- 底部分页 -->
      </div>
      <div class="top" v-loading="lineLoading" style="padding: 10px">
        <div v-if="e2" id="fhqx" style="width: 100%; height: 90%"></div>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { getCompanyListApi } from '@/api/energy-consumption/Equipment-energy/Energy-analysis'
import dayjs from 'dayjs'

import { exportexcel } from '@/utils/excel'
import {
  getLineApi,
  getTableListApi
} from '@/api/energy-consumption/Equipment-energy/Utilization-ratio'
export default {
  name: 'RankingIndex',
  data() {
    return {
      radio: '日',
      form: {},
      tableList: [],
      classId: '',
      title: '',
      date: null,
      lineLoading: false,
      tableLoading: false,
      iissize: 'medium',
      companyList: [],
      UsagePieList: [],
      lineList: [],
      ComparisonLineList: [],
      ProportionData: {},
      e2: true,
      row: {},
      tableConfig: [
        {
          type: 'index',
          align: 'center',
          width: '100px'
        },
        {
          prop: 'companyName',
          label: '用电单位',
          width: '200px'
        },
        {
          align: 'center',
          prop: 'className',
          label: '设备名称',
          width: '200px'
        },
        {
          align: 'right',
          prop: 'loadReading',
          label: '额定功率(kW)',
          formatter: (a, b, c, d) => {
            return Number(c)?.toFixed(2)
          }
        },
        {
          align: 'right',
          prop: 'averageLoad',
          label: '平均负荷(kW)',
          formatter: (a, b, c, d) => {
            return Number(c)?.toFixed(2)
          }
        },
        {
          align: 'right',
          prop: 'averageUtilization',
          label: '平均利用率',
          formatter: (a, b, c, d) => {
            return Number(c)?.toFixed(2) + '%'
          }
        },
        {
          align: 'right',
          prop: 'maxLoad',
          label: '最大负荷(kW)',
          formatter: (a, b, c, d) => {
            return Number(c)?.toFixed(2)
          }
        },
        {
          align: 'right',
          prop: 'maxUtilization',
          label: '最大利用率',
          formatter: (a, b, c, d) => {
            return Number(c)?.toFixed(2) + '%'
          }
        },
        {
          align: 'center',
          prop: 'maxLoadTime',
          label: '最大负荷发生时间'
        },
        {
          align: 'right',
          prop: 'minLoad',
          label: '最小负荷(kW)',
          formatter: (a, b, c, d) => {
            return Number(c)?.toFixed(2)
          }
        },
        {
          align: 'right',
          prop: 'minUtilization',
          label: '最小利用率',
          formatter: (a, b, c, d) => {
            return Number(c)?.toFixed(2) + '%'
          }
        },
        {
          align: 'center',
          prop: 'minLoadTime',
          label: '最小负荷发生时间'
        }
      ]
    }
  },
  watch: {
    radio: {
      handler(newValue) {
        if (this.radio === '日') {
          this.date = dayjs().format('YYYY-MM-DD')
        } else if (this.radio === '月') {
          this.date = dayjs().format('YYYY-MM')
        } else if (this.radio === '年') {
          this.date = dayjs().format('YYYY')
        }
      },
      immediate: true
    },

    date: {
      handler(newValue) {
        if (this.radio === '日') {
          this.date = dayjs(newValue).format('YYYY-MM-DD')
        } else if (this.radio === '月') {
          this.date = dayjs(newValue).format('YYYY-MM')
        } else if (this.radio === '年') {
          this.date = dayjs(newValue).format('YYYY')
        }
      },
      immediate: true,
      deep: true
    }
  },
  async mounted() {
    await this.getCompanyList()
    this.getdatalist()
  },
  methods: {
    companyChange(val) {
      localStorage.setItem('companyId', val)
    },
    async shuaxin() {
      // console.log(this.$refs.table.data)
      await this.getTableList()
      await this.$refs.table.setCurrentRow(
        this.$refs.table.data.find((i) => i.classId == this.classId)
      )
      this.$message({
        type: 'success',
        message: '刷新成功',
        duration: 2000
      })
    },
    // 获取用电企业列表
    async getCompanyList() {
      const res = await getCompanyListApi()
      console.log(res)
      this.companyList = res.data.list
      const companyId = +localStorage.getItem('companyId')
      if (companyId && this.companyList.find((i) => i.id == companyId)) {
        this.$set(this.form, 'companyId', companyId)
      } else {
        this.$set(this.form, 'companyId', this.companyList[0].id)
      }
    },
    // 初始化
    async getchushihua() {
      this.radio = '日'
      this.$set(this.form, 'companyId', this.companyList[0]?.id)
      localStorage.setItem('companyId', this.companyList[0].id)
    },

    // 曲线
    async getLine(id) {
      this.e2 = false
      this.lineLoading = true
      const res = await getLineApi({
        classId: id || '',
        dateType: this.radio === '日' ? 1 : this.radio === '月' ? 2 : 3,
        dateString: this.date
      })
      this.lineList = res.data.list
      this.e2 = true
      this.lineLoading = false
    },

    // 表格
    async getTableList() {
      this.e4 = false
      this.tableLoading = true
      const res = await getTableListApi({
        companyId: this.form.companyId,
        dateString: this.date,
        dateType: this.radio === '日' ? '1' : this.radio === '月' ? '2' : '3',
        pageNo: 0,
        pageSize: 1000
      })
      this.tableList = res.data.list
      this.e4 = true
      this.tableLoading = false
    },
    daochu() {
      exportexcel(
        '/ecm-microservice-biz/ecm/device/utilization/rate/data/exportExcel',
        {
          dateType: this.radio === '日' ? 1 : this.radio === '月' ? 2 : 3,
          dateString: this.date,
          companyId: this.form.companyId
        },
        '设备利用率'
      )
    },
    // 获取数据
    async getdatalist() {
      await this.getTableList()
      if (this.tableList.length > 0) {
        this.$refs.table.setCurrentRow(this.tableList[0])
      } else {
        this.e2 = false
      }
    },
    getLineList(row) {
      if (row) {
        console.log(row)
        this.classId = row.classId
        this.title = row?.className
        this.getLine(row?.classId).then(() => this.myChart())
      }
    },
    myChart(id) {
      const data = this.lineList.map((obj) => {
        return {
          name: obj.name,
          type: 'line',
          smooth: true,
          data: obj.datalist.map((i) => {
            return [i.timeReading, i.valueReading] || []
          })
        }
      })
      console.log(data)
      const myChart = echarts.init(document.getElementById('fhqx'))
      myChart.setOption({
        title: {
          text: this.title
        },
        tooltip: {
          trigger: 'axis'
        },
        legend: {},
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false
          // data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
        },
        yAxis: {
          type: 'value'
        },
        series: data
      })
      window.addEventListener('resize', () => {
        // 图表响应处理
        myChart.resize()
      })
    },
    chaxun() {
      this.getdatalist()
    },

    async chongzhi() {
      await this.getchushihua()
      this.getdatalist()
    },
    command(val) {
      if (val === '默认') {
        this.iissize = 'medium'
      } else if (val === '中等') {
        this.iissize = 'small'
      } else {
        this.iissize = 'mini'
      }
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-select {
  width: 100%;
}

.option {
  height: auto;
}
.dialog-footer {
  display: flex;
  justify-content: center;
}
.tit {
  display: flex;
  align-items: center;
  padding-left: 20px;
  margin-top: 10px;
  font-weight: bold;
  img {
    margin-right: 10px;
  }
}

.bigbox {
  display: flex;
  flex-direction: column;
  padding: 10px;
  background-color: #f1f1f1;
  height: 100%;
  .topbox {
    background-color: #fff;
    padding: 20px;
    box-sizing: border-box;
    height: 80px !important;
    width: 100% !important;
    margin-bottom: 10px;
    // transition-property: all;
    // transition-duration: 0.2s;
  }
  .bodybox {
    flex: 1;
    display: flex;
    flex-direction: column;
    .top {
      display: flex;
      background-color: #fff;
      height: 45%;
      width: 100%;
    }
    .bottom {
      flex: 1;
      background-color: #fff;
      padding: 0 20px;
      .top2 {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 10px;
        .tit2 {
          display: flex;
          align-items: center;

          font-weight: bold;
          img {
            margin-right: 10px;
          }
        }
        .tabs {
          display: flex;
          align-items: center;
          i:hover {
            color: #2194ff;
            cursor: pointer;
          }
        }
      }
    }
  }
}
</style>
